/*
 * @Author: C.
 * @Date: 2023-06-12 10:26:44
 */
// import { ref } from 'vue';
import type { ComputedRef, Ref } from 'vue';
import type {
  BasicTableProps,
  // BasicColumn,
  // GetColumnsParams,
} from '/@/components/Table/src/types/table';
import { useMessage } from '/@/hooks/web/useMessage';
import { usePageContext } from '/~/hooks/component/usePageContext';
import { unref } from 'vue';
interface ActionType {
  getDataSource: <T = Recordable>() => T[];
  // getColumns: (opt?: GetColumnsParams) => BasicColumn[];
  wrapRef: Ref<any>;
}
interface ReturnActionType {
  validTableData: () => Promise<any>;
  validTableDataIsEmpty: (message?: string) => Promise<boolean>;
}
export function useTableValid(
  _: ComputedRef<BasicTableProps>,
  { getDataSource, wrapRef }: ActionType,
): ReturnActionType {
  const { createMessage } = useMessage();
  const pageWrapper = usePageContext();
  async function validTableData() {
    const tableData = getDataSource();
    const validArr: Promise<any>[] = [];
    tableData.forEach((item) => {
      item.validHandles.forEach((f) => {
        validArr.push(f());
      });
    });
    const validResults = await Promise.all(validArr);
    // console.log(validResults);
    const firstCell = validResults.find((item) => !item.result);

    if (firstCell) {
      firstCell && firstCell.cellFocus();
      const message = `表格数据验证失败！第 ${firstCell.index + 1} 行,【${
        firstCell.title
      }】的输入要求为【${firstCell.message}】`;
      createMessage.error(message);
      pageWrapper.focusErrorBlock(unref(wrapRef).offsetTop);
      throw new Error(message);
    }

    return tableData;
  }
  async function validTableDataIsEmpty(message?: string) {
    const tableData = await getDataSource();
    // createMessage.error(message||'表格数据不能为空！')
    const _message = message || '表格数据不能为空！';
    if (tableData.length === 0) {
      createMessage.error(_message);
      pageWrapper.focusErrorBlock(unref(wrapRef).offsetTop);
      throw new Error(message);
    }
    return tableData.length > 0;
  }
  return {
    validTableData,
    validTableDataIsEmpty,
  };
}
